package com.xiaoai.juc;

import java.util.Random;
import java.util.concurrent.Semaphore;

class Parent extends Thread{
    Semaphore wc;
    String name;
    public Parent(Semaphore wc,String name){
        this.wc=wc;
        this.name = name;
    }

    @Override
    public void run() {
        //获取资源
        int availablePermits = wc.availablePermits();
        if (availablePermits>0){
            System.out.println(name+"有茅坑。。。");
        }else {
            System.out.println(name+"没有茅坑了。。。");
        }
        try {
            //获取资源
            wc.acquire(); //获取到资源权限，总数减1,总数
            System.out.println(name+"抢到茅坑--关门，可以上厕所。。。");
            //模拟上厕所时间
            Thread.sleep(new Random().nextInt(1000));
            System.out.println(name+"释放茅坑--开门");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            //释放资源
            wc.release();
        }
    }
}

public class Tbf_Semaphore {
    public static void main(String[] args) throws InterruptedException {
        //最多支持多个资源访问
        Semaphore semaphore = new Semaphore(3);
        for (int i=1;i<=10;i++){
            new Parent(semaphore,"第"+i+"个人,").start();
        }
    }
}